1734F - Zeros and Ones - CodeForces Solution


bitmasks divide and conquer dp math

Please click on ads to support us..

Python Code:

import random

cache = {}

def popcount(n):
    res = 0
    while n:
        res += 1
        n &= n - 1
    return res

def solve(n, k):
    if k == 0:
        return 0
    if k == 1:
        return popcount(n) & 1
    if k % 2 == 1:
        t = solve(n, k - 1)
        x = popcount((k - 1) ^ (n + k - 1)) & 1
                return t + x
    if (n, k) in cache:
        return cache[(n, k)]
    if n % 2 == 0:
        one_cell = 2
        zero_cell = 0
        cnt1 = solve(n // 2, k // 2)
        cnt0 = k // 2 - cnt1
    else:
        one_cell = 0
        zero_cell = 1
        cnt1 = solve(n // 2, k // 2) + solve(n // 2 + 1, k // 2)
        cnt0 = k - cnt1
    res = one_cell * cnt1 + zero_cell * cnt0
        cache[(n, k)] = res
    return res

t = int(input())
for _ in range(t):
    cache.clear()
    n, k = map(int, input().split())
    print(solve(n, k))


Comments

Submit
0 Comments
More Questions

544B - Sea and Islands
152B - Steps
1174D - Ehab and the Expected XOR Problem
1511A - Review Site
1316A - Grade Allocation
838A - Binary Blocks
1515D - Phoenix and Socks
1624D - Palindromes Coloring
1552F - Telepanting
1692G - 2Sort
1191A - Tokitsukaze and Enhancement
903A - Hungry Student Problem
52B - Right Triangles
1712A - Wonderful Permutation
1712D - Empty Graph
1712B - Woeful Permutation
1712C - Sort Zero
1028B - Unnatural Conditions
735B - Urbanization
746C - Tram
1278B - A and B
1353D - Constructing the Array
1269C - Long Beautiful Integer
1076A - Minimizing the String
913C - Party Lemonade
1313A - Fast Food Restaurant
681A - A Good Contest
1585F - Non-equal Neighbours
747A - Display Size
285A - Slightly Decreasing Permutations